<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="产品名称">
          <el-input
            v-model="searchParam.productName"
            placeholder="请输入产品名称"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="生产日期">
          <el-date-picker
            v-model="searchParam.productionDateSearch"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getproductionDate"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button type="primary" plain @click="openSortDialog()"
          >生产顺序调整</el-button
        >
        <el-button type="success" @click="productionDataImport"> 导入 </el-button>
        <el-button
          @click="
            useDownload(
              '/mes/biproductiondata/exportTemp',
              '大屏生产数据上传模板',
              searchParam
            )
          "
        >
          导入模板下载
        </el-button>
        <el-dialog
          title="大屏生产数据数据导入"
          v-model="excelBox"
          width="555px"
        >
          <div>
            <el-button
              @click="
                useDownload(
                  '/mes/biproductiondata/exportTemp',
                  '大屏生产数据上传模板',
                  searchParam
                )
              "
            >
              <template #icon>
                <i-ep-download />
              </template>
              大屏生产数据上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              @click="upload"
              :disabled="uploadBtn"
              style="cursor: pointer"
              >上传</el-button
            >
          </div>
        </el-dialog>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="顺序"
          prop="sort"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="炉批次号"
          prop="furnaceBatch"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="产品名称"
          prop="productName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="产品图号"
          prop="productFigureNumber"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="生产日期"
          prop="productionDate"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ dayjs(scope.row.productionDate).format("YYYY-MM-DD") }}
          </template>
        </el-table-column>
        <el-table-column
          label="炉号"
          prop="equipName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="计划状态"
          prop="planStatus"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("BiProductStatus", scope.row.planStatus) }}
          </template>
        </el-table-column>
        <el-table-column
          label="熔炉状态"
          prop="meltedStatus"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("BiProductStatus", scope.row.meltedStatus) }}
          </template>
        </el-table-column>
        <el-table-column
          label="造型状态"
          prop="modelingStatus"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("BiProductStatus", scope.row.modelingStatus) }}
          </template>
        </el-table-column>
        <el-table-column
          label="浇注状态"
          prop="pouringStatus"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("BiProductStatus", scope.row.pouringStatus) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <biproductiondata-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <biproductiondata-sort
      :visible="sortDialog.visible"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="sortDialog.readvisible"
      @change-visible="changeSortVisible"
    />
    <!--导入-->
    <ImportExcel ref="productionDataImportRef" />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import dayjs from "dayjs";

defineOptions({
  name: "MESBIPRODUCTIONDATA",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/biproductiondata/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  productName: "",
  productionDateSearch: [],
  productionDateStart: "",
  productionDateEnd: "",
};

const deleteParam = {
  api: "/mes/biproductiondata/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

const sortDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/biproductiondata/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开大屏生产数据表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改大屏生产数据";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增大屏生产数据";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开大屏生产数据表单弹窗 */
function openSortDialog() {
  sortDialog.visible = true;
  sortDialog.readvisible = false;
}

/** 打开大屏生产数据表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "大屏生产数据详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function changeSortVisible(value: boolean) {
  sortDialog.visible = value;
  if (!value) {
    sortDialog.data = {};
  }
}

function getproductionDate(data: any) {
  if (data) {
    searchParam.value.productionDateStart = data[0];
    searchParam.value.productionDateEnd = data[1];
  } else {
    searchParam.value.productionDateStart = "";
    searchParam.value.productionDateEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/mes/biproductiondata/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
// 导入excel
const uploadApi = "/mes/biproductiondata/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });
      uploadFile.value = "";
      fileName.value = "";
      excelBox.value = false;
      uploadBtn.value = false;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}
const productionDataImportRef = ref();
async function productionDataImportApiFunc(formdata: FormData, config: any) {
  await request
    .post(uploadApi, formdata, config)
    .then((res: any) => {
      productionDataImportRef.value.resCode = 0;
      if (res.code === 200) {
        ElMessage({
          type: "success",
          message: "上传成功！",
        });
      }
    })
    .catch((e) => {
      productionDataImportRef.value.resCode = 500;
    });
}
const productionDataImport = () => {
  let params = {
    title: "大屏生产数据导入",
    tempApi: "", //模板下载
    importApi: productionDataImportApiFunc, // 导入
    getTableList: getTableList, // 成功后回调
    isShowTemp: false,
    otherParams: {},
  };
  productionDataImportRef.value.acceptParams(params);
};
</script>
